import React, { Component } from 'react';
import { Modal, Form, message, Radio, Button, Icon, Input, Select, Col, Empty,Upload} from 'antd';
import { cityUrls } from '../../utils/city';
import { getToken } from '../../utils/authority';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

export default class NewCutIn extends Component {
    state = {
        value: 1,
        tempType: [],
        imgsrc: "",
        loading:false,
    };

    
    onChange = value => {
        console.log('value', value)
        if (!!value) {
            this.props.dispatch({
                type: 'cutinlib/fetchTempType',
                payload: {
                    matType: value
                }
            });
        } else {
            this.props.dispatch({
                type: 'cutinlib/fetchTempType',
                payload: {
                    matType: 1
                }
            });
        }
        //console.log('radio checked', e.target.value);

    };

    handleChange = info => {
        
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          console.log('info',info)
          const { fileUrl }=  info.file.response.uploadFile
        //   getBase64(info.file.originFileObj, imageUrl =>

        //   );
        this.setState({
            imgsrc:fileUrl,
            loading: false,
          })
        }
      };
    updateMat = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                const { matType, matTemplate, cityId } = values
                this.props.dispatch({
                    type: 'cutinlib/fetchMatUrl',
                    payload: {
                        matType, matTemplate, cityId
                    },
                    callback: (img) => {
                        this.setState({ imgsrc: img,loading:false})
                    },
                });
            }
        })
    }
    submit = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                //console.log('Received values of form: ', values);
                const { imgsrc } = this.state

                this.props.dispatch({
                    type: 'cutinlib/add',
                    payload: { ...values, imeUrl: imgsrc },
                    callback: () => {
                        message.success('添加素材实例成功.');
                        this.props.handleModalVisible(false);
                        this.props.form.resetFields();
                        this.setState({ imgsrc: "" });
                        this.props.onFresh();
                    },
                });
            }
        });
    };

    render() {
        const { modalVisible, form, handleModalVisible, matType, tempType, cityCodes, matExampleUrl } = this.props;
        const uploadButton = (
            <div>
              <Icon type={this.state.loading ? 'loading' : 'plus'} />
              <div className="ant-upload-text">点击上传</div>
            </div>
          );
        return (
            <Modal
                title="新建插播实例"
                forceRender
                visible={modalVisible}
                onOk={this.submit}
                onCancel={() => handleModalVisible(false)}
                footer={[
                    <Button key="back" onClick={() => handleModalVisible(false)}>
                        取消
                    </Button>,
                    <Button type="primary" onClick={this.updateMat}>
                        更新
                    </Button>,
                    <Button key="submit" type="primary" onClick={this.submit} disabled={!this.state.imgsrc}>
                        确定
                    </Button>,
                ]}
            >
                <Form>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="名称">
                        {form.getFieldDecorator('imeName', {
                            rules: [
                                {
                                    required: true,
                                    message: '请勿使用特殊字符',
                                    pattern: RegExp('^[\u4e00-\u9fa5_a-zA-Z0-9]+$'),
                                },
                            ],
                        })(<Input placeholder="请使用汉字、字母和数字" />)}
                    </FormItem>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="插播时长">
                        {form.getFieldDecorator('icPlayTimeLen', {

                        })(<Input placeholder="插播时长" />)}
                    </FormItem>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="素材类型">

                        {form.getFieldDecorator('matType', { rules: [{ required: true, message: '请选择素材类型', }] })(
                            <Select allowClear="true" placeholder="素材类型" style={{ width: '100%' }} onChange={this.onChange}>
                                {matType.map((item, index) => (
                                    <Option value={item.code} key={item.code}>{item.name}</Option>
                                ))}
                            </Select>
                        )}

                    </FormItem>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="模版类型">

                        {form.getFieldDecorator('matTemplate', { rules: [{ required: true, message: '请选择模版类型' }] })(
                            <Select allowClear="true" placeholder="模版类型" style={{ width: '100%' }}>
                                {tempType.map((item, index) => (
                                    <Option value={item.code} key={item.code}>{item.name}</Option>
                                ))}
                            </Select>
                        )}

                    </FormItem>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="城市">

                        {form.getFieldDecorator('cityId', { rules: [{ required: true, message: '请选择城市' }] })(
                            <Select allowClear="true" placeholder="城市" style={{ width: '100%' }}>
                                {cityCodes.map((item, index) => (
                                    <Option value={item.code} key={item.code}>{item.name}</Option>
                                ))}
                            </Select>
                        )}

                    </FormItem>
                    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="图片">
                        <Col span={15}>
                            {/* {this.state.imgsrc ? <img src={this.state.imgsrc} span={15} style={{ width: 200, height: 100 }} /> : <Empty />} */}
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                headers={{
                                    'token': getToken(),
                                  }}
                                action={cityUrls['breakpub'] + `/vehad/v1/uploadFile?token=${getToken()}`}
                            
                                onChange={this.handleChange}
                            >
                                    {this.state.imgsrc  ? <img src={this.state.imgsrc} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>

                        </Col>
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}
